import { IEditorCompleterProps } from './CodeEditorConfig';

/**
 * 重新获取光标所在位置
 * @param data
 * @param column
 * @returns
 */
export function resetEditorPosition(data: string, column: number) {
  let colIdx = column;
  if (data.endsWith('()') || data.endsWith('distinct )')) {
    colIdx = column - 1;
  }
  if (data.endsWith('())')) {
    colIdx = column - 2;
  }

  return colIdx;
}

export let real_table = {}; // {table/db xxx,xxx,xxx,xxx}
export let alias_relation = {}; // 别名 {别名:真实名字}
export let real_table_id = {}; // 存储表的id标识
export let conf = { db_url: '', table_url: 'xxxx', col_url: 'xxxxx' };

// 当用户输入"."时，触发脚本, 获取“.”前面的字符

// o, pos.column
// 从当前位置往前找，遇到空格或“，”号说明遍历完成
function getNameByPos(query: string, pos: number, res: string): any {
  let be = query.substring(pos, pos - 1);

  if (pos <= 0) {
    return res;
  }

  if (be == ' ' || be == ',') {
    return res;
  } else {
    res = be + res;
    return getNameByPos(query, pos - 1, res);
  }
}

/**
 * query
 * pos 点的位置
 * select a.b   ,    a.d from dwa.xxx a;
 * 当分析失败，返回null，不进行自动提醒
 */
export function getPointFontWord(query: string, pos: number) {
  let reg = /\s{2,}/g;
  let res = '';
  let alias = getNameByPos(query, pos, res);
  return alias;
}

/**
 * get table
 * 数组1 id <=>表名
 * 数组2 表名<=>字段 或 db<=>表名
 *
 * */
function getHiveTableByDb(db: string, data: IEditorCompleterProps[]) {
  var tas = data;
  var tables = [];
  for (var j = 0; j < tas.length; j++) {
    const item = tas[j];
    const tid = item.caption;
    const tname = item?.caption || item?.value;
    alias_relation[tname] = tname;
    real_table_id[tname] = tid;
    tables.push(tname);
  }

  if (tables?.length) {
    alias_relation[db] = db;
  }

  real_table[db] = tables.join(',');
}

export function getTableByDb(db: string, data: IEditorCompleterProps[]) {
  if (real_table[db] != undefined) {
    return real_table[db];
  }
  getHiveTableByDb(db, data);
  return real_table[db];
}
